package com.hk.employeemanagementsystem.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hk.employeemanagementsystem.entity.RoleEntity;
import com.hk.employeemanagementsystem.service.RoleEntityService;
import com.hk.employeemanagementsystem.util.web.WebCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author by 何坤
 * @Classname RoleController
 * @Description TODO
 * @Date 2020/2/11 17:27
 */
@RestController
@RequestMapping(value = "/role")
public class RoleController {
    private Logger logger = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private RoleEntityService roleEntityServiceImpl;

    @GetMapping("/get")
    public Map<String, Object> selectAllRole(){
        Map<String, Object> tips = new HashMap<>();
        try {
            List<RoleEntity> roles = roleEntityServiceImpl.list(new QueryWrapper<RoleEntity>().ne("role_id", 1));
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SELECT);
            tips.put("data", roles);
        } catch (Exception e){
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_SELECT);
        }
        return tips;
    }

    @PostMapping(value = "/add")
    public Map<String, Object> addRole(@RequestBody RoleEntity roleEntity){
        Map<String, Object> tips = new HashMap<>();
        try {
            String roleEn = "ROLE_" + roleEntity.getRoleEn();
            roleEntity.setRoleEn(roleEn);
            RoleEntity one = roleEntityServiceImpl.getOne(new QueryWrapper<RoleEntity>().eq("role_role_en", roleEntity.getRoleEn()));
            if (one != null) {
                tips.put("data", 1);
            } else {
                roleEntityServiceImpl.save(roleEntity);
                tips.put("data", 2);
            }
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
        } catch (Exception e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
        }
        return tips;
    }

    @DeleteMapping(value = "/delete/{rid}")
    public Map<String, Object> deleteRoleById(@PathVariable("rid") Integer rid){
        Map<String, Object> tips = new HashMap<>();
        try {
            roleEntityServiceImpl.removeById(rid);
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_DELETE);
        } catch (Exception e) {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_DELETE);
        }
        return tips;
    }
}
